package com.rlyy.basic.resolver.argument;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.rlyy.common.param.Request;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.Optional;

/**
 * 处理参数注解是RequestParam()参数类型是Map解析器
 *
 * @author yuanqinglong
 * @since 2020/9/14 15:32
 */
@Component
public class RequestParamMapMethodArgumentResolver implements MyHandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(Parameter parameter) {
        RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
        if (requestParam == null) {
            return false;
        }
        String key = Optional.ofNullable(Strings.emptyToNull(requestParam.name())).orElseGet(() -> Strings.emptyToNull(requestParam.value()));
        return Map.class.isAssignableFrom(parameter.getType()) && !StringUtils.isEmpty(key);
    }

    @Override
    public Object resolveArgument(Parameter parameter, Request fullRequest) {
        RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
        String key = Optional.ofNullable(Strings.emptyToNull(requestParam.name()))
                .orElseGet(() -> Strings.emptyToNull(requestParam.value()));
        JSONObject jsonObject = Optional.ofNullable(fullRequest.getData())
                .map(d->d.getJSONObject(key)).orElse(null);
        return Optional.ofNullable(jsonObject).map(json -> json.toJavaObject(Map.class))
                .orElse(null);
    }

}
